﻿using System;
using System.IO;
using System.Net;
using DevExpress.XtraEditors;

namespace ContractManager.Common.Service
{
    public sealed class FtpService
    {
        private readonly string _ftpServerIp;
        private readonly string _ftpUserId;
        private readonly string _ftpPassword;

        public FtpService(string ftpServerIp, string ftpUserId, string ftpPassword)
        {
            _ftpServerIp = ftpServerIp;
            this._ftpPassword = ftpPassword;
            this._ftpUserId = ftpUserId;
        }


        public void Download(string remoteDir, string file, DirectoryInfo diSubDir)
        {
            try
            {
                string uri = String.Format(@"ftp://{0}{1}/{2}", _ftpServerIp, remoteDir, file);
                var serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    return;
                }
                var reqFtp = (FtpWebRequest)WebRequest.Create(serverUri);
                reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFtp.UseBinary = true;
                reqFtp.Proxy = null;
                reqFtp.UsePassive = true;
                var response = (FtpWebResponse)reqFtp.GetResponse();
                if (response != null)
                {
                    Stream responseStream = response.GetResponseStream();

                    var writeStream = new FileStream(String.Format(@"{0}\{1}", diSubDir.FullName, file), FileMode.Create);
                    int Length = 8192;
                    var buffer = new Byte[Length];
                    if (responseStream != null)
                    {
                        int bytesRead = responseStream.Read(buffer, 0, Length);
                        while (bytesRead > 0)
                        {
                            writeStream.Write(buffer, 0, bytesRead);
                            bytesRead = responseStream.Read(buffer, 0, Length);
                        }
                    }
                    writeStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }

            }
            catch (WebException wEx)
            {
                XtraMessageBox.Show(wEx.Message, "Download Error");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Download Error");
            }
        }
    }
}
